package httpserver

import (
	"gluenet/internal/agent/api"
	"gluenet/internal/agent/driver/rpcdriver"
	"gluenet/internal/agent/service/transfersvc"
	v1 "gluenet/pkg/log/v1"
	"gluenet/utils/rpc/labels"
	"io"
	"net/http"
)

const (
	transfer = `transfer`
)

func init() {
	registerRouter(api.HTTP_SERVICE_TRANSFER, NewTransferRouter)
}

type transferRouter struct {
	svc *transfersvc.Service
	log v1.Logger
}

func NewTransferRouter(mux *http.ServeMux) {
	log := v1.NewLogger(transfer)
	svc := transfersvc.NewService(log)

	r := &transferRouter{
		svc: svc,
		log: log,
	}

	mux.HandleFunc(api.WriteToManager, r.writeToManager)

}

var topic = rpcdriver.GenUrl(labels.ControlManager, labels.ApplicationReport)

func (rt *transferRouter) writeToManager(w http.ResponseWriter, r *http.Request) {
	data, err := io.ReadAll(r.Body)
	if err != nil {
		rt.log.Errorf("read request body error")
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	rt.svc.PostDataToManager(topic, data)
	w.WriteHeader(http.StatusNoContent)
}
